package com.example.administrator.basepro.ui.presenter;

import com.example.administrator.basepro.base.RxPresenter;
import com.example.administrator.basepro.model.DataManager;
import com.example.administrator.basepro.model.bean.LoginBean;
import com.example.administrator.basepro.ui.contract.LoginContract;
import com.example.administrator.basepro.utils.RxUtil;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by Administrator on 2017/9/1 0001.
 */

public class LoginPresenter extends RxPresenter<LoginContract.View> implements LoginContract.Presenter{

    private DataManager mDataManager;
    @Inject
    public LoginPresenter(DataManager mDataManager) {
        this.mDataManager = mDataManager;
    }

    @Override
    public void login(String username, String password) {

        Map<String,String> map=new HashMap<>();
        map.put("name",username);
        map.put("password",password);
        Gson gson=new Gson();
        String s = gson.toJson(map);
        MediaType JSON= MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON,s);
        addSubscribe(mDataManager.login(body)
        .compose(RxUtil.<LoginBean>rxSchedulerHelper())
        .subscribe(new Consumer<LoginBean>() {
            @Override
            public void accept(@NonNull LoginBean loginBean) throws Exception {
                mView.showLoginInfo(loginBean);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(@NonNull Throwable throwable) throws Exception {
                mView.showLoginError(throwable.getMessage());
            }
        }));
    }

    @Override
    public void register(String username, String password) {
        Map<String,String> map=new HashMap<>();
        map.put("name",username);
        map.put("password",password);
        Gson gson=new Gson();
        String s = gson.toJson(map);

        MediaType JSON= MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON,s);
        addSubscribe(mDataManager.register(body)
                .compose(RxUtil.<LoginBean>rxSchedulerHelper())
                .subscribe(new Consumer<LoginBean>() {
                    @Override
                    public void accept(@NonNull LoginBean loginBean) throws Exception {
                        mView.showRegisterInfo(loginBean);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        mView.showLoginError(throwable.getMessage());
                    }
                }));
    }
}
